class wsConnect {
	constructor({userId,onMsg}) {
		this.wsInstance = null,
		this.isConnect = false
		this.connect(userId,onMsg)
		
	}
	connect = (userId,onMsg) => {
		var _this=this
		this.wsInstance = uni.connectSocket({
			url: 'ws://139.224.164.161:2348',
			header: {
				'content-type': 'application/json'
			},
			success:()=> {
				// console.log('链接ws成功')
					_this.isConnect = true
			},
			complete: () => {}
			
		});

		uni.onSocketOpen(function(res) {
			// console.log('开启了')
		
			
			_this.sendMessage({
					msg: {
						postType: 'register',
						userId: userId
					}
				
			})
			
		});
		
		uni.onSocketMessage(function (res) {
			
		  onMsg(res)
		});
	}
	
	sendMessage = ({msg}) => {
		
		if (this.isConnect) {
			uni.sendSocketMessage({
				data: JSON.stringify(msg),
				success:()=> {
					console.log('发送成功')
				},
				fail:(err)=>{
					uni.showToast({
						title:'发送失败！' //只显示错误时候的消息
					})
					uni.closeSocket(this.wsInstance) //先关闭上一次开启的socket 下一步抛出错误，外界监听到错误重新尝试开启
					throw Error;
				}
			});
		} else {
			
			uni.showToast({
				title:'发送失败，未能链接服务器！' //只显示错误时候的消息
			})
			console.log('发送失败，未能链接服务器！')
				throw Error;
		}
	}
	



}

export default wsConnect